<?php

function reequipment_userapi_getshipping($args)
{
    extract($args);

    /* Fields in table.
		shipping_id
		invoice_number
		cost
		company_id
   */

    // Optional arguments
    if (!isset($startnum)) {$startnum = 1;}
    if (!isset($numitems)) {$numitems = -1;}

    $dbconn =& xarDBGetConn();
    $xartable =& xarDBGetTables();
    $table = $xartable['reshipping'];
    $join_company = $xartable['rel_eq'];
    $join_items = $xartable['reitems'];

    $query = "SELECT DISTINCT s.shipping_id,
    				 s.invoice_number,
					 s.cost,
					 s.company_id,
					 r.company_name,
					 i.last_ordered"
    		. " FROM $table s"
    		
    		. " LEFT OUTER JOIN $join_items i"
    		. " on s.invoice_number = i.invoice_number"
    		
    		. " LEFT OUTER JOIN $join_company r"
    		. " on s.company_id = r.company_id";     		

    $where = array();
    $bind = array();
    
    if (!empty($shipping_id)) {
        $where[] = 's.shipping_id = ?';
        $bind[] = (int)$shipping_id;
    }
    
    if (!empty($invoice_number)) {
        $where[] = 's.invoice_number = ?';
        $bind[] = (string)$invoice_number;
    } 
    
    if (!empty($company_id)) {
        $where[] = 's.company_id = ?';
        $bind[] = (int)$company_id;
    } 
    
    if (!empty($where)) {
        $query .= ' WHERE ' . implode(' AND ', $where);
    }

    // Not really necessary
    $query .= " ORDER BY s.shipping_id";

    $result =& $dbconn->SelectLimit($query, $numitems, $startnum-1, $bind);
    if (!$result) return;

    $tags = array();
    for (; !$result->EOF; $result->MoveNext()) {
        list($shipping_id, $invoice_number, $cost, $company_id, $company_name, $last_ordered) = $result->fields;

        $tags[] = array(
        		'shipping_id'		=> $shipping_id,
        		'invoice_number'	=> xarVarPrepForDisplay($invoice_number),
                'cost' 				=> round($cost, 2),
                'company_id'		=> $company_id,
                'company_name'		=> xarVarPrepForDisplay($company_name),
                'last_ordered'		=> xarLocaleGetFormattedDate('long', $last_ordered)
        );
    }

    $result->Close();
    return $tags;
}
?>